package llama.network;

import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.io.IOException;

import llama.core.LoginCredentials;

import com.esotericsoftware.kryonet.Client;
import com.esotericsoftware.kryonet.Connection;
import com.esotericsoftware.kryonet.Listener;

public class KryoServerConnection extends Listener implements IServerConnection {

	private PropertyChangeSupport pcs = new PropertyChangeSupport(this);
	private Client client = null;
	
	private void init() {
		client = new Client(98304, 10240);
		/**
		 * Uses NetworkRegistration in shared temporarily.
		 */
		NetworkRegistration.register(client);
		client.start();
		client.addListener(this);
	}
	
	@Override
	public void connect(int timeout, String host, int tcpPort) throws IOException {
		if (client == null) {
			init();
		}
		
		client.connect(timeout, host, tcpPort);
	}
	
	@Override
	public boolean isConnected(){
		if(client != null){
			return client.isConnected();
		}
		return false;
	}

	@Override
	public void send(NetworkMessage nm) {
		client.sendTCP(nm);
	}
	
	@Override
	public void authenticate(LoginCredentials lc) {
		client.sendTCP(lc);
	}
	
	@Override
	public void disconnect() {
		client.stop();
		client = null;
	}
	
	/**
	 * Override from kryonet.Listener
	 */
	@Override
	public void received(Connection conn, Object o) {
		if (o instanceof NetworkMessage){
			NetworkMessage nm = (NetworkMessage)o;
			nm.setFromConnectionId(conn.getID());
			System.out.println("Client received: " + ((NetworkMessage) o).getObject().getClass() + ":" + ((NetworkMessage) o).getType());
			pcs.firePropertyChange("received", null, nm);
		}
	}
	
	@Override
	public void disconnected(Connection conn) {
		pcs.firePropertyChange("disconnected", null, new NetworkMessage(null, NetworkMessage.Type.DISCONNECTED));
	}
	
	@Override
	public void addPropertyChangeListener(PropertyChangeListener pcl) {
		pcs.addPropertyChangeListener(pcl);
	}
	
	@Override
	public void removePropertyChangeListener(PropertyChangeListener pcl) {
		pcs.removePropertyChangeListener(pcl);
	}

	

}
